import utils.TreeNode;

/**
 * @Author ZhangCuirong
 * @Date 2025/9/18 11:26
 * @description:
 */
public class LCR143 {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B==null) {
            return false;
        }
        if (isCommon(A, B)) {
            return true;
        }
        boolean left = isSubStructure(A.left, B);
        boolean right = isSubStructure(A.right, B);
        return left || right;
    }

    public boolean isCommon(TreeNode root1, TreeNode root2) {
        if (root2 == null) {
            return true;
        }
        if (root1 == null) {
            return false;
        }
        if (root1.val != root2.val) {
            return false;
        }
        return isCommon(root1.left, root2.left) && isCommon(root1.right, root2.right);
    }

    public static void main(String[] args) {
        LCR143 lcr = new LCR143();
        TreeNode tree1 = TreeNode.buildTree(new int[]{1, 7, 5});
        TreeNode tree2 = TreeNode.buildTree(new int[]{6, 1});
        System.out.println(lcr.isSubStructure(tree1, tree2));

        tree1 = TreeNode.buildTree(new int[]{3, 6, 7, 1, 8});
        tree2 = TreeNode.buildTree(new int[]{6, 1});
        System.out.println(lcr.isSubStructure(tree1, tree2));
    }
}
